package com.shinemo.mpush.alloc.handler;

import com.mpush.api.chat.ChatMessage;
import com.mpush.api.chat.ChatMessageSendResult;
import com.mpush.api.protocol.PushType;
import com.mpush.api.push.*;
import com.mpush.netty.http.HttpClient;
import com.mpush.tools.Jsons;
import com.shinemo.mpush.alloc.common.ResultCode;
import com.shinemo.mpush.alloc.http.HttpRequest;
import com.shinemo.mpush.alloc.http.HttpResponse;
import com.shinemo.mpush.alloc.service.MesIdService;
import com.shinemo.mpush.alloc.vo.BaseResponse;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

/**
 * 处理多条聊天消息的推送，主要用于推送离线聊天消息
 */
public class ChatMessagesHandler implements HttpHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private PushSender pushSender = null;
    private HttpClient httpClient = null;
    private MesIdService mesIdService = null;

    public ChatMessagesHandler(PushSender pushSender, HttpClient httpClient, MesIdService mesIdService) {
        this.pushSender = pushSender;
        this.httpClient = httpClient;
        this.mesIdService = mesIdService;
    }

    @Override
    public void handle(HttpExchange httpExchange) throws IOException {

        BaseResponse response = new BaseResponse();
        try {
            String json = HttpRequest.getBody(httpExchange);
            response = this.sendPush(json);
        } catch (Exception e) {
            logger.error("", e);
            response.setCode(ResultCode.INTERNAL_SERVER_ERROR.getCode());
            response.setMes("内部错误");
        }
        HttpResponse.writeJson(httpExchange, Jsons.toJson(response));
    }

    private BaseResponse sendPush(String json) {

        List<ChatMessage> messages = Jsons.fromJsonToList(json, ChatMessage.class);

        for (ChatMessage message : messages) {
            PushContent pushContent = new PushContent(PushType.CHAT, Jsons.toJson(message));
            PushMsg pushMsg = PushMsg.build(MsgType.NOTIFICATION_AND_MESSAGE, Jsons.toJson(pushContent));
            String mesId = mesIdService.createMesId();
            pushMsg.setMsgId(mesId);

            PushContext pushContext = PushContext.build(pushMsg).setUserId(message.getReceiverId());

            trySend(pushContext);
        }

        BaseResponse response = new BaseResponse();
        response.setCode(ResultCode.SUCCESS.getCode());
        response.setMes("成功");

        return response;
    }

    private void trySend(PushContext pushContext) {
        try {
            pushSender.send(pushContext);
        } catch (Exception e) {
            logger.error("", e);
        }
    }
}
